package com.aiyige.page.my.wallet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.base.eventbus.EventSetWalletPwdSuccess;
import com.aiyige.model.SmsCode;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.login.callbacks.ITimerCallBack;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.VerifyCodeManager;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 设置钱包-验证码页面
 */
@Route(path = ARouterConfig.WalletVerifyCodePage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class WalletVerifyCodePage extends BaseActivity implements ITimerCallBack {


    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_next)
    TextView tvNext;

    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.et_verification_code)
    EditText etVerificationCode;
    SmsCode smsCode;
    boolean isSending = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_wallet_verify_code);
        ButterKnife.bind(this);
        initTitleLayout(getString(R.string.set_wallet_password));
        setAutoRegisterEventBus(true);
        etVerificationCode.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                super.beforeTextChanged(s, start, count, after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                checkInput();
            }
        });
        tvMobile.setText(AccountUtil.getCurrentUser().getMobile());
        sendVerifyCode();
        VerifyCodeManager.getInstance().addLoginCallBack(this);
    }

    private void checkInput() {
        String input = etVerificationCode.getText().toString();
        if (!TextUtils.isEmpty(input) && input.length() >= 4) {
            tvNext.setEnabled(true);
        } else {
            tvNext.setEnabled(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogin event) {
        if (AccountUtil.isLogin() && LoginManager.getInstance().checkBindingPhone()) {
            tvMobile.setText(AccountUtil.getCurrentUser().getMobile());
        }
    }

    private void checkVerifyCode() {
        String code = etVerificationCode.getText().toString();
        if (TextUtils.isEmpty(code) || smsCode == null) {
            ToastX.show("验证码不能为空");
            return;
        }
        String mobile = AccountUtil.getCurrentUser().getMobile();
        if (smsCode != null && !TextUtils.isEmpty(code) && smsCode.getMobile().equals(mobile) && RxTool.Md5(code).equals(smsCode.getCode())) {
            ARouter.getInstance()
                    .build(ARouterConfig.WalletSetPwdPage1)
                    .withString("code", code)
                    .navigation();
        } else {
            ToastX.show("验证码不正确");
        }
    }

    private void sendVerifyCode() {
        if (!LoginManager.getInstance().checkBindingPhone()) {
            return;
        }
        if (isSending) {
            return;
        }

        VerifyCodeManager.getInstance().tCaptchaDialog(this, new VerifyCodeManager.TCaptchaCallBack() {
            @Override
            public void success() {
                isSending = true;
                ApiManager.getService().fetchByMobile(AccountUtil.getCurrentUser().getMobile(), "password").enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                        isSending = false;
                        try {
                            if (response.isSuccessful()) {
                                smsCode = JsonUtil.toObject(response.body().string(), SmsCode.class);
                                VerifyCodeManager.getInstance().start();
                            } else {
                                ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                                onFailure(call, new Throwable(data.getMessage()));
                            }
                        } catch (Exception e) {
                            try {
                                onFailure(call, new Throwable(e.toString()));
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        isSending = false;
                        if (t != null) {
                            ToastX.show(t.getMessage());
                        }
                    }
                });
            }

            @Override
            public void failed() {

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetPwdSuccess(EventSetWalletPwdSuccess eventSetWalletPwdSuccess) {
        if (eventSetWalletPwdSuccess != null) {
            finish();
        }
    }


    @OnClick({R.id.tv_next, R.id.btn_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_next:
                checkVerifyCode();
                break;
            case R.id.btn_send:
                sendVerifyCode();
                break;
        }
    }

    @Override
    public void onTick(long l) {
        //防止计时过程中重复点击
        btnSend.setClickable(false);
        btnSend.setText((l / 1000) + "s");
//        btnSend.setTextColor(ContextCompat.getColor(this,R.color.zwcolor_gray_b1b5c1));
    }

    @Override
    public void onFinish() {
//        btnSend.setTextColor(ContextCompat.getColor(this,R.color.zwcolor_black_111111));
        //重新给Button设置文字
        btnSend.setText(getResources().getString(R.string.get_verification_code));
        //设置可点击
        btnSend.setClickable(true);
    }
}
